/*
 * create by lixy 20150323
 * Just for DMap(tuteng) Project
 * copyright@ 2015
 */
"use strict";

var app = angular.module('manager.star',
    ['ngRoute', 'ngSanitize',
        'ui.router',
        'angular-timeline',
        'angular-scroll-animate']);

var $GLOBAL_USER = 'developer';
// $scope.$on('$stateChangeStart',function(event, toState, toParams, fromState, fromParams){
// //如果是登录页面就不进行处理 retrun
// if(toState.name=='login') return;
//     //comApi是有一个工具类 此处是判断是否登录 登录信息放缓存了
//     if(!comApi.isNotNullAndUndefined($sessionStorage.ustu)){
// //不是登录页面 取消默认跳转 去登录页面
// event.preventDefault();// 取消默认跳转行为
// $state.go("login",{from:toState.name,w:'notLogin'});//跳转到登录界面
// }

// });

app.config(function ($sceDelegateProvider) {
    $sceDelegateProvider.resourceUrlWhitelist([
        'self',
        'http://grafana-zp.58corp.com/**',
        'http://yunchuang.58corp.com/**',
        '**',
        '*']);
});
app.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
        .when('/star', {
            templateUrl: './star.html',
            controller: 'starController'
        })
        .when('/star/dashboard', {
            templateUrl: './pages/dashboard.html',
            controller: 'dashboardController'
        })
        // kanban
        .when('/sre/xinghuo_kanban/:id', {
            templateUrl: './pages/xinghuo_kanban.html',
            controller: 'xinghuoKanbanController'
        })
        // kanban
        .when('/star/luffy_page/:id', {
            templateUrl: './pages/luffy_page.html',
            controller: 'luffyPageController'
        })

        // 实时洞察 insight
        .when('/star/insight/grafana_dapan/:id', {
            templateUrl: './pages/insight/grafana_dapan.html',
            controller: 'grafanaDapanController'
        })
        .when('/star/insight/data_insight', {
            templateUrl: './pages/insight/data_insight.html',
            controller: 'dataInsightController'
        })

        // report
        .when('/star/fk/fengkong_dashboard', {
            templateUrl: './pages/fk/fengkong_dashboard.html',
            controller: 'fengkongDashboardController'
        })

        // report
        .when('/star/report/email_report_list', {
            templateUrl: './pages/report/email_report_list.html',
            controller: 'emailReportListController'
        })
        .when('/star/report/xinghuo/:id', {
            templateUrl: './pages/report/xinghuo.html',
            controller: 'xinghuoController'
        })
        .when('/star/report/xinghuo/:id/:nodeId', {
            templateUrl: './pages/report/xinghuo.html',
            controller: 'xinghuoController'
            //            templateUrl: './pages/report/test.html',
            //            controller: 'testTreeController'
        })
        .when('/star/report/customer_report', {
            templateUrl: './pages/report/customer_report.html',
            controller: 'customerReportController'
        })
        .when('/star/report/user_report', {
            templateUrl: './pages/report/user_report.html',
            controller: 'userReportController'
        })
        .when('/star/report/ad_report', {
            templateUrl: './pages/report/ad_report.html',
            controller: 'adReportController'
        })
        .when('/star/report/etp_report', {
            templateUrl: './pages/report/etp_report.html',
            controller: 'etpReportController'
        })
//        .when('/star/report/summary_report/:dt/:dt2/:topic/:etp/:bu/:info', {
//            templateUrl: './pages/report/summary_report.html',
//            controller: 'summaryReportController'
//        })
        .when('/star/report/summary_report_ent/:dt/:dt2/:topic/:etp/:bu/:info', {
            templateUrl: './pages/report/summary_report_ent.html',
            controller: 'summaryReportEntController'
        })
        .when('/star/report/summary_report_bu/:dt/:dt2/:topic/:etp/:bu/:info', {
            templateUrl: './pages/report/summary_report_bu.html',
            controller: 'summaryReportBuController'
        })
        .when('/star/report/summary_report_info/:dt/:dt2/:topic/:etp/:bu/:info', {
            templateUrl: './pages/report/summary_report_info.html',
            controller: 'summaryReportInfoController'
        })
        .when('/star/report/summary_report_channel/:dt/:dt2/:topic/:etp/:bu/:info', {
            templateUrl: './pages/report/summary_report_channel.html',
            controller: 'summaryReportChannelController'
        })
        .when('/star/report/fengkong', {
            templateUrl: './pages/report/fengkong.html',
            controller: 'fengkongController'
        })

//        .when('/star/report/summary_flow/:topic/:lspm/:slot', {
//            templateUrl: './pages/report/summary_flow.html',
//            controller: 'summaryFlowController'
//        })

        // dapan
        .when('/star/dapan/basic_dashboard/:biz/:appdiv', {
            templateUrl: './pages/dapan/basic_dashboard.html',
            controller: 'basicDashboardController'
        })

        // 维度分析
//        .when('/star/dapan/basic_dim/:appdiv', {
//            templateUrl: './pages/dapan/basic_dim.html',
//            controller: 'basicDimController'
//        })




//        .when('/star/dapan/zhibiao_dashboard', {
//            templateUrl: './pages/dapan/zhibiao_dashboard.html',
//            controller: 'zhibiaoDashboardController'
//        })

//        .when('/star/dapan/zhaopinzhe_dashboard', {
//            templateUrl: './pages/dapan/zhaopinzhe_dashboard.html',
//            controller: 'operationDashboardController'
//        })
//        .when('/star/dapan/qiuzhizhe_dashboard', {
//            templateUrl: './pages/dapan/qiuzhizhe_dashboard.html',
//            controller: 'qiuzhizheDashboardController'
//        })
//        .when('/star/dapan/pingtai_b_dashboard', {
//            templateUrl: './pages/dapan/pingtai_b_dashboard.html',
//            controller: 'pingtaiBDashboardController'
//        })
//        .when('/star/dapan/pingtai_c_dashboard', {
//            templateUrl: './pages/dapan/pingtai_c_dashboard.html',
//            controller: 'pingtaiCDashboardController'
//        })

//        .when('/star/dapan/zhaopinzhe_dim', {
//            templateUrl: './pages/dapan/zhaopinzhe_dim.html',
//            controller: 'zhaopinzheDimController'
//        })


        // detail
        .when('/star/detail/detail_dashboard', {
            templateUrl: './pages/detail/detail_dashboard.html',
            controller: 'detailDashboardController'
        })

        .when('/star/detail/trace_user_list/:id', {
            templateUrl: './pages/detail/trace_user_list.html',
            controller: 'traceUserListController'
        })

        .when('/star/detail/trace_info_list/:id', {
            templateUrl: './pages/detail/trace_info_list.html',
            controller: 'traceInfoListController'
        })

        .when('/star/detail/click_detail_list', {
            templateUrl: './pages/detail/click_detail_list.html',
            controller: 'clickDetailListController'
        })
        .when('/star/detail/exposure_detail_list', {
            templateUrl: './pages/detail/exposure_detail_list.html',
            controller: 'exposureDetailListController'
        })
        .when('/star/detail/resumedelivery_detail_list', {
            templateUrl: './pages/detail/resumedelivery_detail_list.html',
            controller: 'resumedeliveryDetailListController'
        })
        .when('/star/detail/billing_detail_list', {
            templateUrl: './pages/detail/billing_detail_list.html',
            controller: 'billingDetailListController'
        })

        .when('/star/detail/b2c_bill_detail_list', {
            templateUrl: './pages/detail/b2c_bill_detail_list.html',
            controller: 'b2cBillDetailListController'
        })
        .when('/star/detail/axbbill_info_detail_list', {
            templateUrl: './pages/detail/axbbill_info_detail_list.html',
            controller: 'axbbillInfoDetailListController'
        })
        .when('/star/detail/im_open_detail_list', {
            templateUrl: './pages/detail/im_open_detail_list.html',
            controller: 'openDetailListController'
        })
        .when('/star/detail/iminvite_detail_list', {
            templateUrl: './pages/detail/iminvite_detail_list.html',
            controller: 'iminviteDetailListController'
        })
        .when('/star/detail/job_publish_detail_list', {
            templateUrl: './pages/detail/job_publish_detail_list.html',
            controller: 'jobPublishController'
        })

        // 数据地图
        .when('/star/metric/data_map_list', {
            templateUrl: './pages/metric/data_map_list.html',
            controller: 'dataMapListController'
        })
        .when('/star/metric/data_map_add/:type/:id', {
            templateUrl: './pages/metric/data_map_add.html',
            controller: 'dataMapAddController'
        })
        .when('/star/metric/data_map_item/:type/:id', {
            templateUrl: './pages/metric/data_map_item.html',
            controller: 'dataMapItemController'
        })

        // smart dq

        //  数据服务 列表
        .when('/star/content/data_service_list', {
            templateUrl: './pages/content/data_service_list.html',
            controller: 'DataServiceController'
        })
        //  数据服务 单一元素详情
        .when('/star/content/data_service_detail/:id', {
            templateUrl: './pages/content/data_service_detail.html',
            controller: 'DetailController'
        })
        //  数据服务 单一元素修改
        .when('/star/metric2/data_service_modify/:id', {
            templateUrl: './pages/content/data_service_modify.html',
            controller: 'modifyController'
        })
        //  数据服务 单一元素del
        .when('/star/metric2/data_service_del/:id', {
            //templateUrl: './pages/content/data_service_list.html',
            controller: 'delServiceController'
        })
        //  数据服务 添加一个元素
        .when('/star/metric2/data_service_add/', {
            templateUrl: './pages/content/data_service_add.html',
            controller: 'addServiceController'
        })

        .when('/star/content/content_add/:type/:id', {
            templateUrl: './pages/content/content_add.html',
            controller: 'contentAddController'
        })





        // 指标metric管理
        //        .when('/star/metric2/data_metric', {
        //            templateUrl: './pages/metric2/data_metric.html',
        //            controller: 'dataMetricController'
        //        })
        .when('/star/metric2/data_metric_list/:biz', {
            templateUrl: './pages/metric2/data_metric_list.html',
            controller: 'dataMetricListController'
        })
        .when('/star/metric2/data_metric_add/:biz/:id', {
            templateUrl: './pages/metric2/data_metric_add.html',
            controller: 'dataMetricAddController'
        })
        .when('/star/metric2/data_metric_detail/:biz/:id', {
            templateUrl: './pages/metric2/data_metric_detail.html',
            controller: 'dataMetricDetailController'
        })
        .when('/star/metric2/data_metric_dapan/:biz', {
            templateUrl: './pages/metric2/data_metric_dapan.html',
            controller: 'dataMetricDapanListController'
        })
        //        .when('/star/metric2/metric_list', {
        //            templateUrl: './pages/metric2/metric_list.html',
        //            controller: 'metricListController'
        //        })
        //        .when('/star/metric2/metric_add/:id', {
        //            templateUrl: './pages/metric2/metric_add.html',
        //            controller: 'metricAddController'
        //        })
        //        .when('/star/metric2/data_metric_series', {
        //            templateUrl: './pages/metric2/data_metric_series.html',
        //            controller: 'dataMetricSeriesController'
        //        })
        // 仪表盘管理
        .when('/star/metric2/zhibiao/:id/:nodeId', {
            templateUrl: './pages/metric2/zhibiao.html',
            controller: 'zhibiaoController'
        })
        .when('/star/metric2/zhibiao_manage_list', {
            templateUrl: './pages/metric2/zhibiao_manage_list.html',
            controller: 'zhibiaoManageListController'
        })
        .when('/star/metric2/zhibiao_manage_add/:id', {
            templateUrl: './pages/metric2/zhibiao_manage_add.html',
            controller: 'zhibiaoManageAddController'
        })



        // report2 manage
        .when('/star/report2/email_report_list', {
            templateUrl: './pages/report2/email_report_list.html',
            controller: 'emailReportListController'
        })
        .when('/star/report2/email_report_add/:id', {
            templateUrl: './pages/report2/email_report_add.html',
            controller: 'emailReportAddController'
        })
        .when('/star/report2/xinghuo_report_list', {
            templateUrl: './pages/report2/xinghuo_report_list.html',
            controller: 'xinghuoReportListController'
        })
        .when('/star/report2/xinghuo_report_add/:id', {
            templateUrl: './pages/report2/xinghuo_report_add.html',
            controller: 'xinghuoReportAddController'
        })



        // config
        .when('/star/config/dim_define_list/:search', {
            templateUrl: './pages/config/dim_define_list.html',
            controller: 'dimDefineListController'
        })
        .when('/star/config/dim_define_add/:id', {
            templateUrl: './pages/config/dim_define_add.html',
            controller: 'dimDefineAddController'
        })
        .when('/star/config/adtype_define_list', {
            templateUrl: './pages/config/adtype_define_list.html',
            controller: 'adtypeDefineListController'
        })
        .when('/star/config/adtype_define_edit/:id', {
            templateUrl: './pages/config/adtype_define_edit.html',
            controller: 'adtypeDefineEditController'
        })
        .when('/star/config/adtype_define_edit/', {
            templateUrl: './pages/config/adtype_define_edit.html',
            controller: 'adtypeDefineEditController'
        })

        //product_info
        .when('/star/config/product_info_list', {
            templateUrl: './pages/config/product_info_list.html',
            controller: 'productInfoListController'
        })
        .when('/star/config/product_info_edit/:id', {
            templateUrl: './pages/config/product_info_edit.html',
            controller: 'productInfoEditController'
        })
        .when('/star/config/product_info_edit/', {
            templateUrl: './pages/config/product_info_edit.html',
            controller: 'productInfoEditController'
        })

        // negative_feedback
        .when('/star/config/negative_feedback_list', {
            templateUrl: './pages/config/negative_feedback_list.html',
            controller: 'negativeFeedbackListController'
        })
        .when('/star/config/negative_feedback_edit/', {
            templateUrl: './pages/config/negative_feedback_edit.html',
            controller: 'negativeFeedbackEditController'
        })
        .when('/star/config/negative_feedback_edit/:id', {
            templateUrl: './pages/config/negative_feedback_edit.html',
            controller: 'negativeFeedbackEditController'
        })


        // approver_config
        .when('/star/config/approver_config_list', {
            templateUrl: './pages/config/approver_config_list.html',
            controller: 'approverConfigListController'
        })
        .when('/star/config/approver_config_edit/', {
            templateUrl: './pages/config/approver_config_edit.html',
            controller: 'approverConfigEditController'
        })
        .when('/star/config/approver_config_edit/:id', {
            templateUrl: './pages/config/approver_config_edit.html',
            controller: 'approverConfigEditController'
        })


        // help
        .when('/star/help/issue_list', {
            templateUrl: './pages/help/issue_list.html',
            controller: 'issueListController'
        })
        .when('/star/help/helpdoc_list', {
            templateUrl: './pages/help/helpdoc_list.html',
            controller: 'helpdocListController'
        })
        .when('/star/help/ruledoc_list', {
            templateUrl: './pages/help/ruledoc_list.html',
            controller: 'ruledocListController'
        })
        .when('/star/help/my_list', {
            templateUrl: './pages/help/my_list.html',
            controller: 'myListController'
        })
        .when('/star/help/my_password/:id', {
            templateUrl: './pages/help/my_password.html',
            controller: 'myPasswordController'
        })
        .when('/star/no_permission', {
            templateUrl: './no_permission.html',
            controller: 'noPermissionController'
        })

        // kpi
        .when('/onduty/kpi/kpi_master_list', {
            templateUrl: './pages/kpi/kpi_master_list.html',
            controller: 'kpiMasterListController'
        })
        .when('/onduty/kpi/kpi_master_add/:id', {
            templateUrl: './pages/kpi/kpi_master_add.html',
            controller: 'kpiMasterAddController'
        })
        .when('/onduty/kpi/kpi_detail_list/:groupId/:kpiId', {
            templateUrl: './pages/kpi/kpi_detail_list.html',
            controller: 'kpiDetailListController'
        })
        .when('/onduty/kpi/kpi_detail_add/:groupId/:kpiId/:id', {
            templateUrl: './pages/kpi/kpi_detail_add.html',
            controller: 'kpiDetailAddController'
        })
        .when('/onduty/kpi/kpi_report_add/:groupId/:metricId/:id', {
            templateUrl: './pages/kpi/kpi_report_add.html',
            controller: 'kpiReportAddController'
        })
        .when('/onduty/kpi/kpi_report_detail/:groupId/:metricId', {
            templateUrl: './pages/kpi/kpi_report_detail.html',
            controller: 'kpiReportDetailController'
        })
        .when('/onduty/kpi/kpi_report_list', {
            templateUrl: './pages/kpi/kpi_report_list.html',
            controller: 'kpiReportListController'
        })

        .otherwise({
            redirectTo: '/star'
        });
}])

//权限校验
app.run(['$rootScope', '$location', 'userPermissionCheckService', function ($rootScope, $location, userPermissionCheckService) {

    /* 监听路由的状态变化 */
    $rootScope.$on('$routeChangeStart', function (event, msg) {

        console.log('routeChangeStart start');
        var permissionUrl = $location.$$absUrl.split($location.$$host + ':' + $location.$$port)[1]
        if ($location.$$port == 80) {
            permissionUrl = $location.$$absUrl.split($location.$$host)[1]
        }
        if (permissionUrl == '/star/index.html#/star/no_permission') {
            return
        }

        var param = {};
        param.permissionUrl = permissionUrl
        var hasPermission = true
        var procFn = function (response) {
            if (response.data == null || typeof (response.data) == 'undefined') {
                return
            }
            hasPermission = response.data
            if (hasPermission) {
                console.log(permissionUrl + ' pass')
                return
            } else {
                console.log(permissionUrl + ' not pass')
                window.location.href = "/star/index.html#/star/no_permission";
            }
        };
        var errorFn = function (result) {
            console.log('login error: ' + JSON.stringify(result));
            console.error('permission validate error');
        };
        userPermissionCheckService.permissionValidate(param, procFn, errorFn);
        console.log('routeChangeStart end');//todo 407...


    });

    $rootScope.$on('$routeChangeSuccess', function (evt, current, previous) {
        let permissionUrl = $location.$$absUrl.split($location.$$host + ':' + $location.$$port)
        console.log('route have already changed ：' + permissionUrl);
        console.log('route success ........')

        if(typeof($GLOBAL_USER)!='undefined') {
            watermark({ watermark_txt: $GLOBAL_USER });
        }
    });

}])

/* Services */
app.service('userPermissionCheckService', ['ajaxService', function (ajaxService) {

    this.permissionValidate = function (params, successFunction, errorFunction) {
        $.ajax({
            url: "/star/api/basic-service/v1/user_permission/validate.do",//请求路径
            async: false,
            data: JSON.stringify(params),
            type: "POST",//GET
            contentType: 'application/json',
            dataType: "JSON",//需要返回JSON对象(如果Ajax返回的是手动拼接的JSON字符串,需要Key,Value都有引号)
            success: function (response, status, headers, config) {
                if ((response.code == '00000001' || response.code == '-100') && response.data != null && response.data.redirectUrl != null) {
                    window.location = response.data.redirectUrl;
                } else {
                    successFunction(response, status);
                }
            },
            error: function (response) {
                if (response.IsAuthenicated == false) { window.location = "/index.html"; }
                errorFunction(response);
            }
        })

    };

}]);

var user_cookie_tag = "ac_key";
/* Controllers */
app.controller('index', ['$scope', '$location', '$rootScope', '$routeParams', 'indexService', function ($scope, $location, $rootScope, $routeParams, indexService) {
    var vm = $scope.vm = {};
    vm.p = {};
    vm.result = {};

    var errorFn = function (result) {
        alert(result);
    };
    $scope.pingDetail = function () {
        var vm = $scope.vm;
        vm.result.ms = "...";
        var params = {};
        var procFn = function (response) {
            vm.result.ms = response.ms;
            var data = response.data;
            if (data == null) return;
            $GLOBAL_USER = data[0].userName;

            watermark({ watermark_txt: $GLOBAL_USER });
        };
        indexService.pingDetail(params, procFn, errorFn);
    };
    $scope.initializeController = function () {
        vm.result.ms = '';
        $scope.pingDetail();
    };
    $scope.initializeController();
}]);
/* Services */
app.service('indexService', ['ajaxService', function (ajaxService) {
    this.list = function (params, successFunction, errorFunction) {
        ajaxService.AjaxGetWithData(params, "./api/v1/bibcp/xxx/list", successFunction, errorFunction);
    };
    this.pingDetail = function (params, successFunction, errorFunction) {
        ajaxService.AjaxPost(params, "/star/api/basic-service/v1/aaa/pingDetail.do", successFunction, errorFunction);
    };
}]);


app.filter('to_trusted', ['$sce', function ($sce) {
    return function (text) {
        return $sce.trustAsHtml(text);
    };
}]);

function formatColor(value) {
    var color = colorByVal(value);
    return ['<font color="', color, '">', value, '</font>'].join('');
}
function formatColorCtx(value, color) {
    return ['<font color="', color, '">', value, '</font>'].join('');
}


function serialFormatter(value, row, index) {
    return index + 1;
}

app.filter('contentFmt1', function () {
    return function (input) { // input是我们传入的字符串
        var strs = input.split(",");
        return (strs.length > 1) ? strs[0] : input;
    }
});
app.filter('contentFmt2', function () {
    return function (input) { // input是我们传入的字符串
        var strs = input.split(",");
        return (strs.length > 1) ? strs[1] : input;
    }
});


function crudActionFmt(value, row, index) {
    if (value == null) return "-";
    switch (value) {
        //case 0:
        //    return "新建";
        //    break;
        //case 1:
        //    return "修改";
        //    break;
        case 0:
        case 1:
            return "有效";
            break;
        case 2:
            //return "删除";
            return "无效";
            break;
        case 3:
            return "停用";
            break;
        case 4:
            return "提交审批";
        case 5:
            return "审批通过";
            break;
        case 6:
            return "已运行";
        case 7:
            return "已停止";
        default:
            break;
    }
    return value;
}

function strFormatter(value, row, index) {
    if (value == null) return null;
    return value + "";
}


function orderSubTypeFormatter(value, row, index) {
    if (value == null) return null;
    var ret = '';
    if (value == 0) {
        ret = '堂食';//formatColorCtx('堂食','blue');
    } else if (value == 20) {
        ret = '外卖';//formatColorCtx('外卖','green');
    } else if (value == 21) {
        ret = '自提';//formatColorCtx('自提','yellow');
    } else {
        ret = formatColorCtx('未知:' + value, 'red');
    }
    return ret;
}


function reasonFormatter(value, row, index) {
    if (value == null) return null;
    return formatColorCtx(value, 'red');
}



app.filter('checkReasonIDFormatter', function () {
    return function (value) { // value是我们传入的字符串
        return checkReasonIDFormatter(value, null, null);
    }
});
app.filter('hllDtFormatter', function () {
    return function (value) { // value是我们传入的字符串
        return hll2StdTime(value);
    }
});


app.filter("countNameFmt", function () {
    return function (input) { // input是我们传入的字符串
        if (input == null) return null;
        return quataLineName(input);
    }
});
app.filter("countZhuNameFmt", function () {
    return function (input) { // input是我们传入的字符串
        if (input == null) return null;
        return quataZhuName(input);
    }
});
app.filter("linkFmt", function () {
    return function (input) { // input是我们传入的字符串
        if (input == null) return null;
        var keys = input.rowkey.split("^");
        var resonId = keys[keys.length - 1];
        return resonId
    }
});

app.filter("dateFmt", function () {
    return function (input) { // input是我们传入的字符串
        if (input == null) return null;
        var length = input.cntList.length;
        var date = input.cntList[length - 1][0];
        return date
    }
});

app.filter("bigNumFmt", function () {
    return function (input) { // input是我们传入的字符串
        return bigNumFmt(input)
    }
});

app.filter("ratioFmt", function () {
    return function (input) { // input是我们传入的字符串
        if(! input) return input;
        var color = '';
        if(input<0) {
            color = '';
        } else if (input>0) {
            color = '+';
        } else {
            color = '';
        }
        var value = ratioFmt(input);
        return [color, value].join('');
    }
});

// 异常ID可视化
function checkReasonIDFormatter(value, row, index) {
    if (value == null) return null;
    return [value, '-', reasonName(value)].join('');
}


function contextFormatter(value, row, index) {
    if (value == null) return null;
    var ret = '';
    var len = value.length;
    var step = 80;
    for (var i = 0; i < len; i += step) {
        ret += value.substr(i, step);
        ret += "<br/>"
    }
    return ret;
}

function orderKeyFormatter(value, row, index) {// /profiling/:groupID/:shopID/:saasOrderID
    return ['<a href="#/profiling/', row.groupID, '/', row.shopID, '/', value, '" target="_blank">', value, '</a>'].join('');
}

function licenseCheckFmt(value, row, index) {// /profiling/:groupID/:shopID/:saasOrderID
    return ['<a href="#/star/license/license_check/', value, '" target="_blank">', value, '</a>'].join('');
}

function orderIDFmt(value, row, index) {// /profiling/:groupID/:shopID/:saasOrderID
    return ['<a href="#/star/order/mall_order_detail/', value, '" target="_blank">', value, '</a>'].join('');
}

function queryLicenseFmt(value, row, index) {// /profiling/:groupID/:shopID/:saasOrderID
    return ['<a href="#/star/order/mall_order_detail/', value, '" target="_blank">', "开户进度", '</a>'].join('');
}

function merchantDetailFmt(value, row, index) {// /profiling/:groupID/:shopID/:saasOrderID
    return ['<a href="#/star/merchant/merchant_detail/', value, '" target="_blank">', "开户详情", '</a>'].join('');
}

function continueRegisterFmt(value, row, index) {// /profiling/:groupID/:shopID/:saasOrderID
    return ['<a href="" ng-click="continueRegister(', value, ')">', "失败修复", '</a>'].join('');
}


function moneyFixedFmt(value, row, index) {
    if (value == null) return null;
    return value.toFixed(2);
}




function getTsBefore(gap) {
    if (gap == null || gap == 0) gap = 0;
    var today = new Date();
    var before = new Date();
    before.setTime(today.getTime() - 1000 * gap);
    var strYear = before.getFullYear();
    var strDay = before.getDate();
    if (strDay < 10) {
        strDay = "0" + strDay;
    }
    var strMonth = before.getMonth() + 1;
    if (strMonth < 10) {
        strMonth = "0" + strMonth;
    }
    var strHour = before.getHours();
    if (strHour < 10) {
        strHour = "0" + strHour;
    }
    var strMin = before.getMinutes();
    if (strMin < 10) {
        strMin = "0" + strMin;
    }
    var strSec = before.getSeconds();
    if (strSec < 10) {
        strSec = "0" + strSec;
    }
    return ("" + strYear + strMonth + strDay + strHour + strMin + strSec);
}


function getHMBefore(gap) {
    if (gap == null || gap == 0) gap = 0;
    var today = new Date();
    var before = new Date();
    before.setTime(today.getTime() - 1000 * 60 * gap);
    var strYear = before.getFullYear();
    var strDay = before.getDate();
    if (strDay < 10) {
        strDay = "0" + strDay;
    }
    var strMonth = before.getMonth() + 1;
    if (strMonth < 10) {
        strMonth = "0" + strMonth;
    }
    var strHour = before.getHours();
    if (strHour < 10) {
        strHour = "0" + strHour;
    }
    var strMin = before.getMinutes();
    if (strMin < 10) {
        strMin = "0" + strMin;
    }
    return ("" + strYear + strMonth + strDay + strHour + strMin);
}

function getHBefore(gap) {
    if (gap == null || gap == 0) gap = 0;
    var today = new Date();
    var before = new Date();
    before.setTime(today.getTime() - 1000 * 60 * 60 * gap);
    var strYear = before.getFullYear();
    var strDay = before.getDate();
    if (strDay < 10) {
        strDay = "0" + strDay;
    }
    var strMonth = before.getMonth() + 1;
    if (strMonth < 10) {
        strMonth = "0" + strMonth;
    }
    var strHour = before.getHours();
    if (strHour < 10) {
        strHour = "0" + strHour;
    }
    return ("" + strYear + strMonth + strDay + strHour);
}

function getHMDefault(gap) {
    if (gap == null || gap == 0) gap = 0;
    var today = new Date();
    var before = new Date();
    before.setTime(today.getTime() - 1000 * 60 * 60 * gap);
    var strYear = before.getFullYear();
    var strDay = before.getDate();
    if (strDay < 10) {
        strDay = "0" + strDay;
    }
    var strMonth = before.getMonth() + 1;
    if (strMonth < 10) {
        strMonth = "0" + strMonth;
    }
    return ("" + strYear + strMonth + strDay + "0000");
}

//长字符串表格截取显示
function longContentFmt(value, row, index) {
    if (value.length > 20) {
        // $("#message-text").val(value);
        return value.substring(0, 20) + "..." + "<a data-toggle=\"modal\" data-target=\"#exampleModal\" onclick=\"showLongContent(" + index + ")\" href=\"javascript::void(0)\">[详情]</a>";
    } else {
        //return "<div style=\"font-family:'微软雅黑'\">" + value + "</div>";
        return value;
    }
}

function longContentCutFmt(value, row, index) {
    if (value.length > 30) {
        // $("#message-text").val(value);
        return value.substring(0, 30) + "...";
    } else {
        return value;
    }
}

//使用弹框显示所有内容
function showLongContent(index) {
    var element = angular.element($("#message-text"));
    var scope = element.scope();
    scope.$apply(function () {
        scope.index = index;
    });
}

function delete_confirm() {
    return confirm("删除是不可恢复的，你确认要删除吗？");
}

function numberFmt(value, row, index) {
    if (!value) return '';
    return value.replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
}

function add0(m) {
    return m < 10 ? '0' + m : m
}

function dateFormat(value, row, index) {
    //shijianchuo是整数，否则要parseInt转换
    var time = new Date(value);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
}

function hllCurrentTime() {
    //shijianchuo是整数，否则要parseInt转换
    var time = new Date();
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y + add0(m) + add0(d) + add0(h) + add0(mm) + add0(s);
}

//自定义指令实现ng-repeat完成后执行repeatFinish方法
app.directive('repeatFinish', function () {
    return {
        link: function (scope, element, attr) {
//            console.log(scope.$index);
            if (scope.$last == true) {
                console.log('ng-repeat over, will draw chart.');
                scope.$eval(attr.repeatFinish)
            }
        }
    }
});
// hll时间转化为std时间
function hll2StdTime(v) {
    if (v == null) return null;
    v += "";// 将对象转为字符串
    if (v.length == 14) {// 20181112155301
        return [v.substr(0, 4), '-', v.substr(4, 2), '-', v.substr(6, 2), ' ', v.substr(8, 2), ':', v.substr(10, 2), ':', v.substr(12, 2)].join('');
    } else if (v.length == 12) {// 201811121553
        return [v.substr(0, 4), '-', v.substr(4, 2), '-', v.substr(6, 2), ' ', v.substr(8, 2), ':', v.substr(10, 2)].join('');
    } else if (v.length == 8) {// 20181112
        return [v.substr(0, 4), '-', v.substr(4, 2), '-', v.substr(6, 2)].join('');
    }
}
function hll2StdTimeFmt(value, row, index) {
    // var sourcesize = {data:value};
    return hll2StdTime(value);
}
function objFmt(value, row, index) {
    return JSON.stringify(value);
}


function statusFormatter(value, row, index) {
    if (value == null) {
        return "-";
    }
    switch (value) {
        case 0:
            return "未使用";
        case 1:
            return "已使用";
        default:
            return "-";
    }
}

function productDetailFmt(value, row, index) {
    if (value == null) {
        return "-";
    }
    var arr = [];
    var items = value.split(';');
    for (var i = 0; i < items.length; ++i) {
        var it = items[i];
        var vals = it.split(',');
        //var str = ['[',vals[0],']',vals[3],':',vals[2]].join('');
        var str = [vals[3], ':', vals[2]].join('');
        arr.push(str);
    }
    return arr.join('<br/>');
}



function subBillStatusFormatter(value, row, index) {
    if (value == null) {
        return "-";
    }
    switch (value) {
        case 0:
        case 1:
            return "待接单";
        case 2:
            return "待发货";
        case 3:
            return "已收货";
        case 4:
            return "待结算";
        case 5:
            return "已完成";
        case 6:
            return "已取消";
        case 7:
            return "拒收";
        default:
            return "-";
    }
}

function payTypeFormatter(value, row, index) {
    if (value == null) {
        return "-";
    }
    switch (value) {
        case 0:
        case 1:
            return "货到付款";
        case 2:
            return "账期支付";
        case 3:
            return "线上支付";
        default:
            return "-";
    }
}

function isTestFmt(value, row, index) {
    if (value == null) {
        return "-";
    }
    var typeName = '';
    switch (value) {
        case 0:
            typeName = "正常";
            break;
        case 1:
            typeName = "<font color='red'>测试</font>";
            break;
        default:
            typeName = "-";
            break;
    }
    return typeName;
    //return [value,'-',typeName].join('')
}

function productDetailListJsonFmt(value, row, index) {
    if (value == null || value == 'null') {
        return "-";
    }
    var rows = [];
    var items = JSON.parse(value);
    for (var i = 0; i < items.length; ++i) {
        var data = items[i];
        rows.push(['产品名称：', data['productName'], ", 出库数量：", data['productNumber']].join(''));
    }
    return rows.join('<br/>')
}


function reasonTypeFormatter(value, row, index) {// /profiling/:groupID/:shopID/:saasOrderID
    return [value, '<a href="http://help.hualala.com/pages/viewpage.action?pageId=3146289" target="_blank">帮助</a>'].join('');
}

//function transOrderID2LicenseFmt(value, row, index) {// /profiling/:groupID/:shopID/:saasOrderID
//    return ['<a href="#/star/license/license_list/', value, '" target="_blank">', value , '</a>'].join('');
//}


function deliverOptFmt(value, row, index) {
    if (value == null) {
        return "-";
    }
    return [
        '<a href="#/star/order/tfz_order_deliver_add/', value, '/', row.transOrderID, '" target="_blank">', "<u>编辑查看</u>", '</a>',
        '<a href="#/star/order/tfz_order_deliver_review/', value, '/', row.transOrderID, '" target="_blank">', " <u>申请提交</u>", '</a>'
    ].join('');
}

function productIDFmt(value, row, index) {
    return ['<a href="#/star/product/product_add/', value, '" target="_blank"> ', "编辑", '</a>'].join('');
}


var datetimePicker = function (pickerId, inputId) {
    $(function () {
        //初始化日期控件
        $('#' + pickerId).datetimepicker({
            format: "yyyy-mm-dd",
            weekStart: 1,
            todayBtn: 1,
            autoclose: 1,
            todayHighlight: 1,
            startView: 2,
            forceParse: 0,
            startDate: "2015-01-01",
            minView: 2,
            showMeridian: 1,
            language: "zh-CN"
        });
        //初始化日期控件的输入框
        $('#' + inputId).val(getDateStr(-1));
    });
};

Date.prototype.add = function (part, value) {
    value *= 1;
    if (isNaN(value)) {
        value = 0;
    }
    switch (part) {
        case "y":
            this.setFullYear(this.getFullYear() + value);
            break;
        case "m":
            this.setMonth(this.getMonth() + value);
            break;
        case "d":
            this.setDate(this.getDate() + value);
            break;
        case "h":
            this.setHours(this.getHours() + value);
            break;
        case "n":
            this.setMinutes(this.getMinutes() + value);
            break;
        case "s":
            this.setSeconds(this.getSeconds() + value);
            break;
        default:

    }
};

var getDay = function (gap) {
    if (gap == null || gap == 0) gap = 0;
    var today = new Date();
    var yesterday = new Date();
    yesterday.setTime(today.getTime() - 1000 * 60 * 60 * 24 * gap);
    var strYear = yesterday.getFullYear();
    var strDay = yesterday.getDate();
    if (strDay < 10) {
        strDay = "0" + strDay;
    }
    var strMonth = yesterday.getMonth() + 1;
    if (strMonth < 10) {
        strMonth = "0" + strMonth;
    }
    return "" + strYear + strMonth + strDay;
    //return "20150402";
};

Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1,
        // month
        "d+": this.getDate(),
        // day
        "h+": this.getHours(),
        // hour
        "m+": this.getMinutes(),
        // minute
        "s+": this.getSeconds(),
        // second
        "q+": Math.floor((this.getMonth() + 3) / 3),
        // quarter
        "S": this.getMilliseconds()
        // millisecond
    };
    if (/(y+)/.test(format) || /(Y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};


function getNowFormatDate(diff) {
    var day = new Date();
    day.setDate(day.getDate() + diff);
    var Year = 0;
    var Month = 0;
    var Day = 0;
    var CurrentDate = "";
    Year = day.getFullYear();//支持IE和火狐浏览器.
    Month = day.getMonth() + 1;
    Day = day.getDate();
    CurrentDate += Year;
    if (Month >= 10) {
        CurrentDate += Month;
    }
    else {
        CurrentDate += "0" + Month;
    }
    if (Day >= 10) {
        CurrentDate += Day;
    }
    else {
        CurrentDate += "0" + Day;
    }
    return CurrentDate;
}
//获取时间粒度对应的日期字符串
function getDateStr(addDayCount, timeGranularity) {
    var dd = new Date();
    dd.setDate(dd.getDate() + addDayCount);
    // 获取AddDayCount天后的日期
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1;
    // 获取当前月份的日期
    var d = dd.getDate();

    var space = "";
    if (m < 10) {
        space = "0";
    }
    var spaceD = "";
    if (d < 10) {
        spaceD = "0";
    }
    if (timeGranularity == 2) {
        return y + "-" + space + "" + m;
    } else if (timeGranularity == 3) {
        return y + "";
    } else {
        return y + "-" + space + "" + m + "-" + spaceD + d;
    }
}

function isTestUserFmt(value, row, index) {
    if (value == null) {
        return "-";
    }
    switch (value) {
        case 0:
            return "正式";
        case 1:
            return "测试";
        default:
            return "-";
    }
}

function userStatusFmt(value, row, index) {
    if (value == null) {
        return "-";
    }
    switch (value) {
        case 0:
            return "离职";
        case 1:
            return "在岗";
        default:
            return "-";
    }
}
function rowActionFmt(value, row, index) {
    if (value == null) {
        return "-";
    }
    switch (value) {
        case 0:
            return "新建";
        case 1:
            return "修改";
        case 2:
            return "删除";
        default:
            return "-";
    }
}

// 数字千分位处理
function numberFmt(num) {
    if (num == null) return num;
    var numArr = (num + '').split('.');
    var str = numArr[0];
    var result = '';
    while (str.length > 3) {
        result = ',' + str.slice(-3) + result;
        str = str.slice(0, str.length - 3);
    }
    if (str) {
        result = str + result;
    }
    if (numArr.length > 1) {
        result = result + '.' + numArr[1];
    }
    return result
}

function loadingTemplate(message) {
    return '<i class="fa fa-spinner fa-spin fa-fw fa-2x"></i>'
}

function tableLoadingTemplate(message) {
    // return '<div style="width: 100%;height: 100%;padding: 0;margin: 0;" class="ph-item"><div style="width: 100%;height: 100%;padding: 0;margin: 0;" class="ph-picture"></div></div>'
    // return '<div class="ph-item"><div class="ph-picture"></div></div>'
    return '<i class="fa fa-spinner fa-spin fa-fw fa-2x"></i>'
}

// 将data list转化为tree的方式
function list2Tree(data) {
    var tree = [];
    // 匹配节点
    var findText = function(arr, text) {
        var idx = -1;
        for(var i=0;i<arr.length;++i) {
            if(arr[i].text==text) {
                idx = i;
                break;
            }
        }
        return idx;
    };
    var addNode = function(tree, node1, leaf) {
        var node1Obj;
        var node1Idx = findText(tree, node1);
        if(node1Idx==-1) {
            node1Obj = {text: node1, nodes:[]};
            tree.push(node1Obj);
        }else {
            node1Obj = tree[node1Idx];
        }
        node1Obj.nodes.push(leaf);
    };
    for(var i=0; i<data.length; ++i) {
        addNode(tree,data[i].topicGroup, data[i].topic);
    }
    return tree;
}


// 将data dim list转化为tree的方式
function dim2Tree(data) {
    var tree = [];
    // 匹配节点
    var findText = function(arr, text) {
        var idx = -1;
        for(var i=0;i<arr.length;++i) {
            if(arr[i].text==text) {
                idx = i;
                break;
            }
        }
        return idx;
    };
    var addNode = function(tree, node1, leaf) {
        var node1Obj;
        var node1Idx = findText(tree, node1);
        if(node1Idx==-1) {
            node1Obj = {text: node1, nodes:[]};
            tree.push(node1Obj);
        }else {
            node1Obj = tree[node1Idx];
        }
        node1Obj.nodes.push({text:leaf});
    };

    for(var i=0; i<data.length; ++i) {
        var key = data[i].itemKey;
        var items = data[i].itemValue.split(",");
        for(var it=0; it<items.length; ++it) {
            addNode(tree,key, items[it]);
        }
    }
    return tree;
}

function readTopicGroupEn(topicGroup) {
    if (topicGroup==null) {
        return '-';
    }
    var idx = topicGroup.indexOf("（");
    return topicGroup.substr(idx+1, 2);
}

function add0(m) {
    return m < 10 ? '0' + m : m
}

function hllCurrentDt(n) {
    var current = new Date();
    var time = new Date(current.getTime() + n*24*60*60*1000);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    return y + add0(m) + add0(d);
}